package com.leetcode.partition12;

import java.io.*;
import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2022/1/31 17:43
 */
public class LC1135最低成本联通所有城市 {

    private static final int N = 10010, M = 10010;
    private static int n = 0, m = 0;
    private static int[] parent = new int[N];
    private static int[][] edges = new int[M][3];

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] ss = reader.readLine().split(" ");
        int n = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]);
        int[][] conn = new int[m][3];
        for (int i = 0; i < m; i++) {
            ss = reader.readLine().split(" ");
            int a = Integer.parseInt(ss[0]), b = Integer.parseInt(ss[1]), c = Integer.parseInt(ss[2]);
            conn[i] = new int[]{a, b, c};
        }
        writer.write(minimumCost(n, conn) + "\n");
        writer.flush();
    }

    public static int minimumCost(int _n, int[][] connections) {
        n = _n;
        m = connections.length;
        edges = connections;
        if (m < n - 1) return -1;
        for (int i = 0; i < N; i++) parent[i] = i;
        Arrays.sort(edges, 0, m, (o1, o2) -> Integer.compare(o1[2], o2[2]));
        int ans = 0;
        for (int k = 0; k < m; k++) {
            int a = edges[k][0], b = edges[k][1], c = edges[k][2];
            int x = find(a), y = find(b);
            if (x != y) {
                ans += c;
                parent[x] = y;
            }
        }
        return ans;
    }

    private static int find(int x) {
        if (x == parent[x]) return x;
        return parent[x] = find(parent[x]);
    }
}
